package com.example.xViewChat.Service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.example.xViewChat.Bean.IntentBean;
import com.example.xViewChat.NettyClient.CacheTools;
import com.example.xViewChat.NettyClient.ConnectorManager;
import com.example.xViewChat.NettyClient.PushManager;
import io.ganguo.chat.core.transport.IMResponse;

/**
 * Created by hasee on 2016-03-31.
 */
public class PushService extends Service {

    protected final static int DEF_PORT = 28888;
    private ConnectorManager manager;

    @Override
    public void onCreate() {
        manager = ConnectorManager.getManager(this.getApplicationContext());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String action;
        if (intent == null) {
            intent = new Intent(PushManager.ACTION_CONNECTION);
            String host = CacheTools.getString(this, CacheTools.KEY_SERVIER_HOST);
            int port = CacheTools.getInt(this, CacheTools.KEY_SERVIER_PORT);
            intent.putExtra(CacheTools.KEY_SERVIER_HOST, host);
            intent.putExtra(CacheTools.KEY_SERVIER_PORT, port);
        }

        action = intent.getStringExtra(PushManager.SERVICE_ACTION);

        if (PushManager.ACTION_CONNECTION.equals(action)) {
            String host = intent.getStringExtra(CacheTools.KEY_SERVIER_HOST);
            int port = intent.getIntExtra(CacheTools.KEY_SERVIER_PORT, DEF_PORT);
            manager.connect(host, port);
        }

        if (PushManager.ACTION_SENDREQUEST.equals(action)) {
            IntentBean intentBean = (IntentBean) intent.getSerializableExtra(PushManager.KEY_SEND_BODY);

            manager.send(intentBean);
        }

        if(PushManager.ACTION_DESTORY.equals(action))
        {
            manager.destroy();
            this.stopSelf();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        return Service.START_REDELIVER_INTENT;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
